package com.ganlucode.sipmock.sip.request.impl.msg;

import com.ganlucode.sipmock.gb28181.constants.XmlNode;
import lombok.extern.slf4j.Slf4j;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import javax.sip.RequestEvent;
import javax.sip.message.Request;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

/**
 * @author GanLu
 * @date 2020-05-18 15:44
 */
@Slf4j
public class BaseMessageProcessor {

    private static final String yyyy_MM_dd_T_HH_mm_ss_SSSXXX = "yyyy-MM-dd'T'HH:mm:ss";
    private static final String yyyy_MM_dd_HH_mm_ss = "yyyy-MM-dd HH:mm:ss";

    protected Element getRootElement(RequestEvent evt) throws DocumentException {
        Request request = evt.getRequest();
        SAXReader reader = new SAXReader();
        reader.setEncoding(XmlNode.XML_ENCODING);
        InputStream inputStream = new ByteArrayInputStream(request.getRawContent());
        Document xml = reader.read(inputStream);
        return xml.getRootElement();
    }

    protected String getResponseXml(RequestEvent evt) throws DocumentException {
        Element root = getRootElement(evt);
        return root.getDocument().asXML();
    }

    protected Date parseISO8601Time(String formatTime){
        SimpleDateFormat sdf = new SimpleDateFormat(yyyy_MM_dd_T_HH_mm_ss_SSSXXX, Locale.getDefault());
        try {
            return sdf.parse(formatTime);
        } catch (ParseException e) {
            log.error("时间解析错误",e);
        }
        return null;
    }
}
